<template>
  <div class="register-dialog">
    <el-dialog
      title
      width="600px"
      :visible.sync="registerDialogVisible"
      :before-close="handleClose"
      :close-on-click-modal="false"
      :modal-append-to-body="false"
    >
      <div slot="title" class="title">
        <img src="static/darklogo.png" />
        <p>个人版注册</p>
      </div>
      <el-form :model="form" :rules="rules" ref="ruleForm" status-icon>
        <el-form-item prop="userName">
          <el-popover trigger="hover">
            <ul>
              <li>6-20个字符，支持字母数字及“@”、“-”、“.”，请勿包含身份证银行卡等隐私信息</li>
              <li>一旦设置成功不能更改</li>
            </ul>
            <el-input slot="reference" v-model.trim="form.userName" placeholder="用户名"></el-input>
          </el-popover>
        </el-form-item>
        <el-form-item prop="password">
          <validate-pwd ref="validatePwd" v-model="form.password" @setPassword="setPassword"></validate-pwd>
        </el-form-item>
        <el-form-item v-if="registerMethods" prop="phone">
          <el-input v-model="form.phone">
            <template slot="prepend">+86</template>
          </el-input>
        </el-form-item>
        <el-form-item v-else prop="email">
          <el-input placeholder="请输入邮箱" v-model="form.email"></el-input>
        </el-form-item>
        <el-form-item prop="slider" class="slider">
          <verify-slider
            v-model="form.slider"
            ref="slider"
            tips="请按住滑块，拖动到最后"
            @success="slideSuccess"
          ></verify-slider>
        </el-form-item>
        <el-form-item prop="identifyCode" class="identify-code">
          <el-input v-model="form.identifyCode" placeholder="验证码">
            <template slot="append">
              <el-button
                @click="getVCode"
                :disabled="identifyCodeMsg !== '获取验证码'"
              >{{ identifyCodeMsg }}</el-button>
            </template>
          </el-input>
          <div class="code-error" v-show="validateCodeError">验证码错误</div>
        </el-form-item>
        <div class="register-methods flex between">
          <p
            class="pointer href"
            @click="changeRegisterMethods"
          >使用{{ registerMethods ? '邮箱' : '手机' }}注册</p>
          <p>
            已有账号?
            <span class="pointer href" @click="login">登录</span>
          </p>
        </div>
        <div class="register-btn black-btn">
          <el-button :loading="loading" @click="registe">注册</el-button>
        </div>
        <el-form-item prop="policy" class="policy">
          <el-checkbox v-model="form.policy">
            <span>
              我已阅读并同意
              <a href="https://cue.group/privacy.html" target="_blank">《开域集团隐私政策》</a>
            </span>
          </el-checkbox>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>
<script>
import { VerifySlider } from 'vue-verify-slider'
import ValidatePwd from '@/components/ValidatePwd'
export default {
  components: {
    VerifySlider,
    ValidatePwd
  },
  data() {
    const validateUserName = (rule, value, callback) => {
      // eslint-disable-next-line no-useless-escape
      const reg = /^[(a-zA-Z0-9){1}\-\@\.]{6,20}$/
      // eslint-disable-next-line no-control-regex
      const str = value.replace(/[^\x00-\xff]/g, 'xx').length // 中文转换为两个字符
      if (!value) {
        return callback(new Error('用户名不能为空'))
      } else if (str < 6 || str > 20) {
        return callback(new Error('用户名长度需为6-20个字符'))
      } else if (!reg.test(value)) {
        return callback(new Error('用户名只支持字母数字及“@”、“-”、“.”'))
      } else {
        const params = {
          userName: value
        }
        this.$http.post(this.$service.checkUserName, params).then(res => {
          if (res.value) {
            return callback(new Error('用户名已存在'))
          } else {
            return callback()
          }
        })
      }
    }
    const validatePwd = (rule, value, callback) => {
      const reg = /(?!^[0-9]+$)(?!^[A-z]+$)(?!^[^A-z0-9]+$)^.{6,20}$/
      const reg2 = /^[^ ]+$/ // 判断密码是否包含空格
      if (!value) {
        return callback(new Error('密码不能为空'))
      } else if (!reg2.test(value)) {
        return callback(new Error('密码只能包含数字字母、标点符号（空格除外）'))
      } else if (value.length < 6 || value.length > 20) {
        return callback(new Error('密码长度需为6-20个字符'))
      } else if (!reg.test(value)) {
        return callback(new Error('密码强度不符合要求'))
      } else {
        return callback()
      }
    }
    const validatePhone = (rule, value, callback) => {
      const reg = /^1(3|4|5|7|8)\d{9}$/
      if (!value) {
        return callback(new Error('手机号不能为空'))
      } else if (!reg.test(value)) {
        return callback(new Error('请输入正确的手机号'))
      } else {
        const params = {
          mobileNumber: value
        }
        this.$http.post(this.$service.checkPhoneNumber, params).then(res => {
          if (res.value) {
            return callback(new Error('手机号已被其他账号绑定'))
          } else {
            return callback()
          }
        })
      }
    }
    const validateEmail = (rule, value, callback) => {
      const reg = /^[A-Za-z\d]+([-_.][A-Za-z\d]+)*@([A-Za-z\d]+[-_.])+[A-Za-z]{2,5}$/
      if (!value) {
        return callback(new Error('邮箱不能为空'))
      } else if (!reg.test(value)) {
        return callback(new Error('请输入正确的邮箱地址'))
      } else {
        const params = {
          email: value
        }
        this.$http.post(this.$service.checkEmail, params).then(res => {
          if (res.value) {
            return callback(new Error('邮箱已被其他账号绑定'))
          } else {
            return callback()
          }
        })
      }
    }
    const validateSlider = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('请完成人机验证'))
      } else {
        return callback()
      }
    }
    const validateIdentifyCode = (rule, value, callback) => {
      if (!value) {
        this.validateCodeError = false
        return callback(new Error('验证码不能为空'))
      } else {
        return callback()
      }
    }
    const validatePolicy = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('请阅读并同意隐私政策'))
      } else {
        return callback()
      }
    }
    return {
      registerDialogVisible: false,
      identifyCodeMsg: '获取验证码',
      form: {
        userName: '',
        password: '',
        phone: '',
        email: '',
        slider: false,
        identifyCode: '',
        policy: false
      },
      rules: {
        userName: [{ validator: validateUserName, trigger: 'blur' }],
        password: [{ validator: validatePwd, trigger: 'blur' }],
        phone: [{ validator: validatePhone, trigger: 'blur' }],
        email: [{ validator: validateEmail, trigger: 'blur' }],
        slider: [{ validator: validateSlider }],
        identifyCode: [{ validator: validateIdentifyCode, trigger: 'blur' }],
        policy: [{ validator: validatePolicy, trigger: 'change' }]
      },
      timer: '',
      loading: false,
      registerMethods: true,
      validateCodeError: false
    }
  },
  methods: {
    slideSuccess() {
      this.form.slider = true
      this.$el.querySelector('.slider .el-form-item__error').style.display =
        'none'
    },
    setPassword(value) {
      this.form.password = value
    },
    handleClose() {
      this.registerDialogVisible = false
      this.validateCodeError = false
      this.registerMethods = true
      this.$refs.validatePwd.pwdStatus = true
      this.$refs.slider.init()
      this.$refs.ruleForm.resetFields()
      clearInterval(this.timer)
      this.identifyCodeMsg = '获取验证码'
    },
    // 获取验证码
    getVCode() {
      this.$refs.ruleForm.validateField(
        this.registerMethods ? 'phone' : 'email',
        valid => {
          if (!valid) {
            this.$refs.ruleForm.validateField('slider', () => {
              if (this.form.slider) {
                let time = 60
                this.timer = setInterval(() => {
                  this.identifyCodeMsg = time + 's 后重新获取'
                  time--
                  if (time < 0) {
                    clearInterval(this.timer)
                    this.identifyCodeMsg = '获取验证码'
                  }
                }, 1000)
                const params = {
                  uname: this.registerMethods
                    ? this.form.phone
                    : this.form.email,
                  pid: 210
                }
                this.$http.post(this.$service.getVCode, params).then(res => {
                  const vCode = res.data.vCode
                  if (this.registerMethods) {
                    const info = {
                      appId: 'cue_frontend',
                      appToken: 'c890195cd04f0afffcc118812d83dca6',
                      mobiles: [this.form.phone],
                      msgContent: `尊敬的用户，本次操作验证码：${vCode}，10分钟内有效，请勿泄露。`,
                      msgSignature: '【开域集团】'
                    }
                    this.$http.post(this.$service.sendPhoneVCode, info)
                  } else {
                    const params = {
                      email: this.form.email,
                      title: 'test',
                      content: `尊敬的用户，本次操作验证码：${vCode}，10分钟内有效，请勿泄露。`,
                      emailAddress: 'dvp_service@cue.group',
                      emailAddressName: '开域集团',
                      password: 'Abcd56789'
                    }
                    this.$http.post(this.$service.sendEmailCode, params)
                  }
                })
              }
            })
          }
        }
      )
    },
    changeRegisterMethods() {
      this.$refs.ruleForm.clearValidate()
      this.registerMethods = !this.registerMethods
    },
    login() {
      const href = 'http://l-test19.dev.cn2.corp.agrant.cn:9990/#/login?relogin="true"'
      window.open(href, '_blank')
    },
    registe() {
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          const params = {
            uname: this.registerMethods ? this.form.phone : this.form.email,
            vCode: this.form.identifyCode,
            pid: 210
          }
          this.$http.post(this.$service.validateVCode, params).then(res => {
            this.validateCodeError = !res.data.validate
            if (res.data.validate) {
              this.loading = true
              const params = {
                customerInfoDto: {
                  agent: -1,
                  cname: this.form.userName,
                  tel: this.form.phone,
                  email: this.form.email,
                  status: 0
                },
                userInfoDto: {
                  password: this.form.password,
                  uname: this.form.userName,
                  telephone: this.form.phone,
                  email: this.form.email
                }
              }
              this.$http
                .post(this.$service.registerUser, params)
                .then(res => {
                  if (res.message === '成功') {
                    this.$router.push('validateSuccess')
                  }
                }).finally(() => {
                  this.loading = false
                })
            }
          })
        }
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.register-dialog {
  .title {
    text-align: center;
    font-size: 14px;
    line-height: 20px;
    img {
      height: 0.18rem;
    }
  }
  .el-dialog {
    .identify-code {
      span {
        color: #909399;
        cursor: pointer;
      }
    }
    .register-methods {
      line-height: 0;
      margin-bottom: 22px;
      p {
        color: #000;
      }
      .href {
        color: #546ffc;
      }
    }
    .register-btn {
      .el-button {
        width: 100%;
      }
    }
    .code-error {
      font-size: 12px;
      color: #f56c6c;
      line-height: 1;
      position: absolute;
      top: 45px;
    }
    .policy {
      span {
        color: #000;
      }
      a {
        color: #546ffc !important;
      }
    }
    .drag {
      width: 100%;
      .drag_bg {
        width: 100% !important;
      }
    }
  }
}
</style>
